package com.heima.behavior.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavvior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private CacheService cacheService;


    /**
     * 保存记录用户阅读量行为
     * 存放到redis中
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1 检查参数
        if(dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 判断用户是否登录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3 更新文章阅读量  key=READ_BEHAVIOR+文章id，hashkey=用户id，value=JSON序列化后的dto
        String readBeaviorJson = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId().toString(), apUser.getId().toString());
        if(StringUtils.isNotBlank(readBeaviorJson)){
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readBeaviorJson, ReadBehaviorDto.class);
            dto.setCount((short) (readBehaviorDto.getCount()+dto.getCount()));
        }

        //4 保存到redis中
        log.info("阅读量行为：保存当前key：{}，{}，{}",dto.getArticleId(),apUser.getId(),dto);
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId().toString(),apUser.getId().toString(),JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
